#
# Copyright Thoughtworks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# 根据系统配置设置Rails国际化语言
Rails.application.config.after_initialize do
  Rails.logger.info "[I18N] === I18n Initializer Starting ==="

  begin
    Rails.logger.info "[I18N] Creating SystemEnvironment instance..."
    # 获取Java系统环境配置
    system_environment = com.thoughtworks.go.util.SystemEnvironment.new
    Rails.logger.info "[I18N] SystemEnvironment instance created successfully"

    Rails.logger.info "[I18N] Calling getEffectiveUILanguage()..."
    # 获取有效语言设置
    effective_language = system_environment.getEffectiveUILanguage()
    Rails.logger.info "[I18N] getEffectiveUILanguage() returned: #{effective_language}"

    Rails.logger.info "[I18N] Setting I18n.locale to: #{effective_language}"
    # 设置Rails I18n语言
    I18n.locale = effective_language.to_sym
    Rails.logger.info "[I18N] I18n.locale set to: #{I18n.locale}"

    Rails.logger.info "[I18N] Setting I18n.default_locale to: #{effective_language}"
    I18n.default_locale = effective_language.to_sym
    Rails.logger.info "[I18N] I18n.default_locale set to: #{I18n.default_locale}"

    Rails.logger.info "[I18N] === I18n Initializer Completed Successfully ==="
    Rails.logger.info "[I18N] GoCD UI Language set to: #{effective_language}"
  rescue => e
    Rails.logger.error "=== I18n Initializer Failed ==="
    Rails.logger.error "Exception: #{e.class}: #{e.message}"
    Rails.logger.error "Backtrace: #{e.backtrace.join("\n")}"

    # 如果出错，使用默认英文
    Rails.logger.warn "Falling back to default English locale"
    I18n.locale = :en
    I18n.default_locale = :en
    Rails.logger.warn "Failed to set UI language, using default English: #{e.message}"
  end
end